import { baseUrl } from '@/config.js'

export class Request {
  constructor(options = {}) {
    this.baseUrl = options.baseUrl || baseUrl
    this.interceptors = {
      request: null,
      response: null
    }
    this.loadingCount = 0; // 新增加载计数器
  }

  // 设置拦截器
  setInterceptor(request, response) {
    this.interceptors.request = request
    this.interceptors.response = response
  }

  async request(options) {
    // 请求拦截
    if (this.interceptors.request) {
      options = this.interceptors.request(options)
    }

    // 合并请求参数
    options.url = this.baseUrl + options.url
    options.header = {
      'Content-Type': 'application/json',
      'Authorization': uni.getStorageSync('token'),
      ...options.header
    }

    // 处理加载提示
    const loadingText = options.loadingText || '加载中...';
    
    try {
      this.loadingCount++;
      if(this.loadingCount === 1) {
        uni.showLoading({ 
          title: loadingText,
          mask: true 
        });
      }

      const response = await new Promise((resolve, reject) => {
        options.complete = (res) => {
          // 响应拦截
          if (this.interceptors.response) {
            res = this.interceptors.response(res)
          }
          
          if (res.code >= 200 && res.code < 300) {
            resolve(res.data)
          } else {
            reject(res)
          }
        }
        uni.request(options)
      })
      return response
    } catch (error) {
      this._handleError(error)
      throw error
    } finally {
      this.loadingCount--;
      if(this.loadingCount === 0) {
        uni.hideLoading();
      }
    }
  }

  get(url, data, options = {}) {
    return this.request({
      url,
      data,
      method: 'GET',
      ...options
    })
  }

  post(url, data, options = {}) {
    return this.request({
      url,
      data,
      method: 'POST',
      ...options
    })
  }

  _handleError(error) {
    const status = error.code
    const messageMap = {
      400: '请求参数错误',
      401: '登录已过期',
      403: '没有权限',
      404: '资源不存在',
      500: '服务器错误'
    }

    uni.showToast({
      title: messageMap[status] || '网络请求失败',
      icon: 'none',
      duration: 2000
    })

    if (status === 401) {
      uni.navigateTo({ url: '/pages/login/index' })
    }
  }
}

// 创建请求实例并导出
export const request = new Request()